var currentPage = 1;
var rowsPerPage = 15;

var addButton = $('.btn.btn-primary[data-bind="click: add"]');
var pageCountSection = $('span.page-count');

var moveFirstButton = $('.pagination-button.move-first-button');
var movePreviousButton = $('.pagination-button.move-previous-button');
var moveNextButton = $('.pagination-button.move-next-button');
var moveLastButton = $('.pagination-button.move-last-button');

var TraineeModel = function(trainee) {

	var self = this;

	self.Id = trainee.Id;

	self.Username = trainee.Username;

	self.Password = trainee.Password;

	self.WithAccount = ko.computed(function() {
		return (self.Username.trim() != '');
	});

	self.Gender = ko.observable(trainee.Gender);

	self.FirstName = ko.observable(trainee.FirstName);

	self.MiddleName = ko.observable(trainee.MiddleName);

	self.LastName = ko.observable(trainee.LastName);

	self.FullName = ko.computed(function() {
		var name = '';

		var gender = 'brother';

		try {
			gender = self.Gender().toLowerCase().trim();
		}
		catch (ex) {

		}

		if (gender == 'brother') name = 'Bro. ';
		else name = 'Sis. ';
		
		try {
			name += self.FirstName().trim() + ' ' + self.LastName().trim();
		}
		catch (ex) {

		}

		
		return name;
	});

	self.BirthDate = ko.observable(trainee.BirthDate);
	self.Age = ko.computed(function() {
		var age = 0;

		var dob = new Date();

		try {
			dob = new Date(Date.parse(self.BirthDate()));
		}
		catch (ex) {

		}

		var now = new Date();
		age = now.diff(dob, 'year');

		return age;
	});

	self.Nationality = ko.observable(trainee.Country);
	self.Locality = ko.observable(trainee.Locality);
	self.District = ko.observable(trainee.District);
	self.Addresses = ko.observableArray(ko.utils.arrayMap(trainee.Addresses, function(address) {
		var model = {
			Id: address.Id,
			UnitNo: address.UnitNo,
			Street: address.Street,
			Subdivision: address.Subdivision,
			Area: address.Area,
			Country: address.Country,
			Locality: address.Locality,
			FullAddress: ko.computed(function() {
				var fullAddress = '';

				fullAddress = address.UnitNo.trim();

				if (address.Street.trim() != '') {
					if (fullAddress.trim() != '') fullAddress += ' ' + address.Street.trim();
					else fullAddress = address.Street.trim();


					fullAddress += ' Street';
				}

				if (address.Subdivision.trim() != '') {
					if (fullAddress.trim() != '') fullAddress += ', ' + address.Subdivision.trim();
					else fullAddress = address.Subdivision.trim();

					fullAddress += ' Subdivision';
				}

				if (address.Area.trim() != '') {
					if (fullAddress.trim() != '') fullAddress += ', ' + address.Area.trim();
					else fullAddress = address.Area.trim();
				}

				if (address.Locality.trim() != '') {
					if (fullAddress.trim() != '') fullAddress += ', ' + address.Locality.trim();
					else fullAddress = address.Locality.trim();
				}

				if (address.Country.trim() != '') {
					if (fullAddress.trim() != '') fullAddress += ', ' + address.Country.trim();
					else fullAddress = address.Country.trim();
				}

				return fullAddress;					
			})
		};

		return model;
	}));
	
	self.PhoneNo = ko.computed(function() {
		var phoneNo = 'NA';
		if (trainee.PhoneNo.trim() != '') phoneNo = trainee.PhoneNo;
		return 'Phone No. : ' + phoneNo;
	});

	self.MobileNo = ko.computed(function() {
		var mobileNo = 'NA';
		if (trainee.MobileNo.trim() != '') mobileNo = trainee.MobileNo;
		return 'Mobile No. : ' + mobileNo;
	});

	self.ContactNo = ko.observable(trainee.ContactNo);
	self.Email = ko.observable(trainee.Email);
	
	self.MailTo = ko.computed(function() {
		var mailTo = '';
		var email = '';

		try {
			email = self.Email();
		}
		catch (ex) {

		}
		
		if (email.trim() != '') mailTo = 'mailto:' + email.trim();

		return mailTo;
	});

	self.DateBaptized = ko.observable(trainee.DateBaptized);
	self.BaptismalLocation = ko.observable(trainee.BaptismalLocation);
	self.Image = ko.observable(trainee.Image);

	self.ImageSource = ko.computed(function() {
		var imgSrc = '';
		
		try {
			imgSrc = self.Image();
		}
		catch (ex) {

		}

		if (imgSrc.trim() == '') {
			var gender = 'brother';

			try {
				gender = self.Gender();
			}
			catch (ex) {

			}

			if (gender.toLowerCase() == 'sister') imgSrc =  app.baseUrl() + 'img/sis.png';
			else imgSrc = app.baseUrl() + 'img/bro.png';
		}

		return imgSrc;
	});

	self.RowState = 'unchanged';

} ;

var TraineesModel = function(trainees) {

	var self = this;

	self.currentPage = ko.observable(currentPage);

	self.trainees = ko.observableArray(ko.utils.arrayMap(trainees, function(trainee) {
		var viewModel = new TraineeModel(trainee);
		return viewModel;
	}));

	self.add = function() {
		if (addButton.hasClass('disabled')) return;
		else addButton.addClass('disabled');

		var view = 'trainee-info';

		$.post(app.baseUrl() + 'index.php/home/setView', {
			'view' : view
		}).done(function(data) {
			if (data == view) {
				$.post(app.baseUrl() + 'index.php/home/setTraineeId', {
					'id' : 0
				}).done(function(response) {
					if (response == 0) window.location.replace(app.baseUrl());
				}).fail(function(response) {
					try {
						console.error(response);
					}
					catch (ex) {

					}
				}).always(function() {
					addButton.removeClass('disabled');
				});
			}
		}).fail(function(response) {
			try {
				console.error(response);
			}
			catch (ex) {

			}

			addButton.removeClass('disabled');
		}).always(function() {
			
		});
	};

	self.moveFirst = function() {
		if (currentPage > 1) {
			currentPage = 1;
			self.currentPage(currentPage);
			moveNextButton.closest('li').removeClass('disabled');
			moveLastButton.closest('li').removeClass('disabled');
			if (!movePreviousButton.closest('li').hasClass('disabled')) movePreviousButton.closest('li').addClass('disabled');
			if (!moveFirstButton.closest('li').hasClass('disabled')) moveFirstButton.closest('li').addClass('disabled');
			self.refresh();
		}
	};

	self.moveLast = function() {
		var maxPage = pageCountSection.text();

		if (currentPage != maxPage) {
			currentPage = maxPage;
			self.currentPage(currentPage);
			movePreviousButton.closest('li').removeClass('disabled');
			moveFirstButton.closest('li').removeClass('disabled');
			if (!moveNextButton.hasClass('disabled')) moveNextButton.closest('li').addClass('disabled');
			if (!moveLastButton.hasClass('disabled')) moveLastButton.closest('li').addClass('disabled');
			self.refresh();
		}
	};

	self.moveNext = function() {
		var maxPage = pageCountSection.text();

		if (currentPage != maxPage) {
			currentPage += 1;
			self.currentPage(currentPage);

			movePreviousButton.closest('li').removeClass('disabled');
			moveFirstButton.closest('li').removeClass('disabled');
				
			if (currentPage >= maxPage) {
				if (!moveNextButton.hasClass('disabled')) moveNextButton.closest('li').addClass('disabled');
				if (!moveLastButton.hasClass('disabled')) moveLastButton.closest('li').addClass('disabled');
			}
			
			self.refresh();
		}
	};

	self.movePrevious = function() {
		if (currentPage > 1) {
			currentPage -= 1;
			self.currentPage(currentPage);

			moveNextButton.closest('li').removeClass('disabled');
			moveLastButton.closest('li').removeClass('disabled');
				
			if (currentPage <= 1) {
				if (!movePreviousButton.hasClass('disabled')) movePreviousButton.closest('li').addClass('disabled');
				if (!moveFirstButton.hasClass('disabled')) moveFirstButton.closest('li').addClass('disabled');
			}
			
			self.refresh();
		}
	};

	self.refresh = function() {
		var container = $('.table-container');
		app.loader( { 'container': container } );

		$.post(app.baseUrl() + 'index.php/references/paginatedTrainees', {
			page: currentPage,
			rows: rowsPerPage
		}).done(function(response) {
			var trainees = null;

			try {
				trainees = JSON.parse(response);
			}
			catch (ex) {

			}

			if (trainees.length != undefined) {
				var models = [];

				for (i = 0; i < trainees.length; i++) {
					models.push(new TraineeModel(trainees[i]));
				}

				self.trainees(models);

				var table = $('.trainees-table');
				table.floatThead({
				    scrollContainer: function(refTable){
						return refTable.closest('.table-container');
					}
				});

				setRemoveTraineeToolTips();
			}
		}).fail(function(response) {
			try {
				console.error(response);
			}
			catch (ex) {

			}

			errorGritter({
				title: 'Oooops',
				text: 'Something went wrong while trying to load the data to be displayed.'
			});
		}).always(function() {
			app.loader('hide');
		});
	};

	self.remove = function(trainee) {
		messageBox.show({
			title: 'Delete Trainee',
			message: 'Remove <strong>' + trainee.FullName() + '</strong> from the list of trainees?<br /><br />\n' +
					'<p class="text-danger"><strong>Note :</strong> If you proceed, records related with this trainee\'s information (ea. training records) will also be removed.</p>',
			buttons: [
				{ caption: 'Yes' },
				{ caption: 'No' }
			],
			buttonSelected: function(e) {
				if (e.button.caption.toLowerCase().trim() == 'yes') {
					if (!e.sender.hasClass('disabled')) {
						e.sender.addClass('disabled');

						var id = trainee.Id;
						
						var info = {
							Id: id,
							Email: trainee.Email(),
							RowState: 'deleted'
						};

						data = { 'trainee': info };

						$.ajax({
						    type: 'POST',
						    url: app.baseUrl() + 'index.php/references/update',
						    data: { 'data' : JSON.stringify(data) },
						    dataType: 'json'
						}).done(function(response) {
							var saved = true;
							var message = '';

							if (response != undefined &&
								response != null) {
								if (response.saved != undefined) {
									if (response.saved != null) saved = response.saved;
								}

								if (response.message != undefined) {
									if (response.message != null) message = response.message;
 								}
							}

							e.messageBox.modal('hide');

							if (saved) {
								unsetRemoveTraineeToolTips();
								self.trainees.remove(trainee);
								setRemoveTraineeToolTips();
							}
							else {
								if (message.trim() == '') message = 'Unable to permanently delete trainee record. Please try again.';
								
								warningGritter({
									title: 'Delete Trainee',
									text: message
								});						
							}
						}).fail(function(response) {
							e.messageBox.modal('hide');

							try {
								console.error(response);
							}
							catch (ex) {

							}

							errorGritter({
								title: 'Oooops',
								text: 'Something went wrong while trying to send the request into the server.'
							});
						}).always(function() {
							e.sender.removeClass('disabled');
						});
					}

					e.cancel = true;

					return e;
				}
			}
		});
	}

	self.view = function(trainee) {
		var id = trainee.Id;

		var view = 'trainee-info';

		$.post(app.baseUrl() + 'index.php/home/setView', {
			'view' : view
		}).done(function(data) {
			if (data == view) {
				$.post(app.baseUrl() + 'index.php/home/setTraineeId', {
					'id' : id
				}).done(function(response) {
					if (response == id) window.location.replace(app.baseUrl());
				}).fail(function(response) {
					try {
						console.error(response);
					}
					catch (ex) {

					}
				}).always(function() {
					addButton.removeClass('disabled');
				});
			}
		}).fail(function(response) {
			try {
				console.error(response);
			}
			catch (ex) {

			}

			addButton.removeClass('disabled');
		}).always(function() {
			
		});	
	};

	self.viewAccount = function(trainee) {

	};
	
};

var refreshView = function() {
	var container = $('.table-container');
	app.loader( { 'container': container } );

	$.post(app.baseUrl() + 'index.php/references/paginatedTrainees', {
		page: currentPage,
		rows: rowsPerPage
	}).done(function(response) {
		var trainees = null;

		try {
			trainees = JSON.parse(response);
		}
		catch (ex) {

		}

		if (trainees != null) {
			ko.applyBindings(new TraineesModel(trainees));

			var table = $('.trainees-table');
			table.floatThead({
			    scrollContainer: function(refTable){
					return refTable.closest('.table-container');
				}
			});

			setRemoveTraineeToolTips();
		}
	}).fail(function(response) {
		try {
			console.error(response);
		}
		catch (ex) {

		}

		errorGritter({
			title: 'Oooops',
			text: 'Something went wrong while trying to load the data to be displayed.'
		});
	}).always(function() {
		app.loader('hide');
	});
};

var setRemoveTraineeToolTips = function() {
	unsetRemoveTraineeToolTips();
	var removeLinks = $('a.remove-record-button');
	removeLinks.tooltip( { 
			'title' : 'Permanently remove trainee from the list.',
			'trigger' : 'hover',
			'container' : 'body' 
		} 
	);

	var viewLinks = $('a.view-record-button');
	viewLinks.tooltip({
		'title' : 'View trainee\'s full information.',
		'trigger' : 'hover',
		'container' : 'body' 
	});
};

var unsetRemoveTraineeToolTips = function() {
	var removeLinks = $('a.remove-record-button');
	removeLinks.tooltip('destroy');

	var viewLinks = $('a.view-record-button');
	viewLinks.tooltip('destroy');
};

$(document).ready(function() {
	var tableContainer = $('.table-container.trainees-container');
	try {
		rowsPerPage = tableContainer.attr('data-rows-per-page');
	}
	catch (ex) {

	}

	refreshView();
});